package com.web44.springmvc.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @Title: CrosFIlter
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/16 13:45
 */
public class CrosFIlter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // Access-Control-Allow-Origin
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        // 可以自定义可以跨域的请求头
        response.setHeader("Access-Control-Allow-Headers", "Origin,request-origin,Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token,X-Token");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
